using GroupSix.Domain.Entity;
using GroupSix.Domain.Repositories;
using GroupSix.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace GroupSix.Infrastructure.Reposoitories;

public class EfRepository<T> : IRepository<T> where T : EntityBase
{
    protected readonly GroupSixDbContext _db;

    protected readonly DbSet<T> _tb;

    public EfRepository(GroupSixDbContext dbContext)
    {
        _db = dbContext;
        _tb = dbContext.Set<T>();
    }


    public async Task<T?> CreateAsync(T entity)
    {
        var obj = await _tb.AddAsync(entity);
         await _db.SaveChangesAsync();
        return obj.Entity;
    }

    public async Task DeleteAsync(T entity)
    {
        entity.IsDeleted = true;
        await UpdateAsync(entity);
    }

    public async Task DeleteAsync(Guid id)
    {
        var obj = await GetByIdAsync(id);
        if (obj == null)
        {
            return;
        }
        await DeleteAsync(obj);
    }

    public async Task DeleteHardAsync(Guid id)
    {
        // 硬删除
        var obj = await GetByIdAsync(id);
        if (obj == null)
        {
            return;
        }
        _tb.Remove(obj);
        await _db.SaveChangesAsync();
    }

    public async Task<IEnumerable<T>> GetAllAsync()
    {
        var list = await _tb.AsNoTracking().Where(x => x.IsDeleted == false).ToListAsync();
        return list;
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
        var obj = await _tb.FirstOrDefaultAsync(x => x.Id == id && !x.IsDeleted);
        return obj;
    }

    public async Task UpdateAsync(T entity)
    {
        entity.UpdatedAt = DateTime.UtcNow;
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }
}